import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "订单列表", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },

    showAfterSales: false,
    imageURL: "https://zntg.swehszn.com/file/WechatIMG637.png",
    orderList: [],
    orderHandleList: [],
    orderCompleteList: [],
    status: -1
  },

  onLoad(options) {
    this.mallOrderList()
  },

  onShow() {

  },

  //申请售后
  orderApplyAfterSale() {
    this.mallOrderList()
    this.setData({
      status: -1
    })
  },

  // 获取订单列表
  async mallOrderList() {
    const pageNum = 1;
    const pageSize = 1000;
    try {
      const res = await request({
        url: indexApi.mallOrderListApi(pageNum, pageSize),
        data: {}
      });

      this.setData({
        orderList: res.data.data.records
      })

      console.log("获取订单列表", this.data.orderList);
      this.orderStatistical()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //处理中
  async mallOrderAfterList(event) {
    const status = event.currentTarget.dataset.status
    console.log("处理中", status);
    const pageNum = 1;
    const pageSize = 1000;
    try {
      const res = await request({
        url: indexApi.mallOrderAfterListApi(pageNum, pageSize, status),
        data: {}
      });
      console.log("订单完成", res.data);
      this.setData({
        orderList: res.data.data.records,
        status
      })

      console.log("处理中", this.data.orderList);
      this.orderStatistical()

    } catch (error) {
      console.error("Error:", error);
    }
  },

  //完成售后
  orderCompleteAfterSale() {

  },

  //商品总数量和商品总价
  orderStatistical() {
    this.data.orderList.forEach(order => {
      let totalGoodsCount = 0;
      let totalGoodsSubtotal = 0.0;
      order.products.forEach(product => {
        totalGoodsCount += parseInt(product.goodsCount);
        totalGoodsSubtotal += parseFloat(product.goodsSubtotal);
      });
      order.totalGoodsCount = totalGoodsCount;
      order.totalGoodsSubtotal = totalGoodsSubtotal.toFixed(2);
    });

    // 更新数据
    this.setData({
      orderList: this.data.orderList
    });

    console.log("统计后的订单列表", this.data.orderList);

  },

  //申请售后
  applyAfterSales(event) {
    console.log("选择的订单", event);
    wx.setStorageSync('afterSalesOrder', event.currentTarget.dataset.orderitem);
    wx.setStorageSync('status', this.data.status);
    wx.navigateTo({
      url: '/packageUserCenter/pages/returnRefund/index',
    })
  },
  //审核中
  toExamine(event) {
    wx.setStorageSync('status', this.data.status);
    console.log("this.data.status", this.data.status);
    wx.setStorageSync('afterSalesOrder', event.currentTarget.dataset.orderitem);
    wx.navigateTo({
      url: '/packageUserCenter/pages/writeSales/index',
    })
  }

})